<template>
  <div class="department-container">
    <div class="app-container">
      <!-- 具体页面结构 -->
      <PageTools>
        <template #left>
          <span> 总共：{{ total }} 条数据 </span>
        </template>
        <template #right>
          <el-button size="small" type="warning" @click="$router.push('/employees/import')">导入 Excel</el-button>
          <el-button v-allow="'export_excel'" size="small" type="danger" @click="hExport">导出 Excel</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>
      <el-card v-loading="loading" style="margin-top: 20px">
        <el-table :data="employees" border>
          <el-table-column label="序号" type="index" width="60" align="center" sortable />
          <el-table-column label="姓名" prop="username" align="center" sortable />
          <el-table-column label="头像" align="center" sortable>
            <template v-slot="{ row }">
              <!-- <img class="img" :src="row.staffPhoto" alt=""> -->
              <ImageHolder class="img" :src="row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" align="center" sortable />
          <el-table-column label="聘用形式" align="center" sortable>
            <template v-slot="{ row }">
              {{ formatEmployment(row.formOfEmployment) || '未知' }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" align="center" sortable />
          <el-table-column label="入职时间" align="center" sortable>
            <template v-slot="{ row }">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" align="center">
            <template v-slot="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination :current-page="q.page" :page-sizes="[10, 20, 30, 4]" :page-size="q.size" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-row>
      </el-card>
    </div>
    <el-dialog :visible.sync="showDialog" title="新增员工" width="40%" :close-on-click-modal="false" :close-on-press-escape="false">
      <EmpDialog ref="empDialog" @cancel="showDialog = false" @success="success" @closed="hClosed" />
    </el-dialog>

    <el-dialog :visible.sync="showDialogRole" title="分配角色" width="40%" :close-on-click-modal="false" :close-on-press-escape="false" @closed="$refs.AssignRole.resetRoleIds()">
      <AssignRole :id="curId" ref="AssignRole" :show-dialog-role.sync="showDialogRole" />
    </el-dialog>
  </div>
</template>

<script>
// 引入组件
import { delEmployee, getEmployee } from '@/api/employee'
import Employee from '@/constant/employees'
import EmpDialog from './empDialog.vue'
import AssignRole from './assignRole'
import dayjs from 'dayjs'
const EmployeeList = Employee.hireType.reduce(
  (prv, item) => ({ ...prv, [item.id]: item.value }),
  {}
)
export default {
  components: { EmpDialog, AssignRole },
  data() {
    return {
      employees: [],
      total: 0,
      q: {
        page: 1,
        size: 10
      },
      loading: false,
      showDialog: false,
      showDialogRole: false,
      curId: ''
    }
  },
  created() {
    this.getEmployee()
  },
  methods: {
    async getEmployee() {
      this.loading = true
      const { data } = await getEmployee(this.q)
      this.total = data.total
      this.employees = data.rows
      this.loading = false
    },
    // 聘用形式状态判断
    // 根据枚举文件夹中的值来返回对应的聘用状态
    formatEmployment(code) {
      // const result = Employee.hireType.find(item => item.id === code)
      // if (result) {
      //   return result.value
      // } else {
      //   return '未知'
      // }
      return EmployeeList[code]
    },
    handleSizeChange(size) {
      this.q.size = size
      this.getEmployee()
    },
    handleCurrentChange(page) {
      this.q.page = page
      this.getEmployee()
    },
    // 删除角色
    async hDel(id) {
      try {
        await this.$confirm('该操作会永久删除角色，确定吗？', '提示', {
          type: 'warning'
        })
        const res = await delEmployee(id)
        if (this.employees.length === 1 && this.q.page > 1) {
          this.q.page--
        }
        this.$message.success(res.message)
        this.getEmployee()
      } catch (e) {
        if (e === 'cancel') return
        this.$message.error(e.message)
      }
    },
    // 添加成功之后的回调
    success() {
      // 关闭 dialog
      this.showDialog = false
      this.total++
      // 算出最后一页是第几页，赋值给 q.page
      this.q.page = Math.ceil(this.total / this.q.size)
      // 重新获取数据
      this.getEmployee()
    },
    // 格式化时间
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD')
    },
    hClosed() {
      this.$refs.empDialog.resetForm()
    },
    // 导出 excel
    async hExport() {
      const res = await getEmployee({ page: 1, size: this.total })
      const list = this.formatJson(res.data.rows)
      if (!list[0]) return
      const header = Object.keys(list[0])
      const data = list.map((item) => {
        item['聘用形式'] = EmployeeList[item['聘用形式']]
        return Object.values(item)
      })
      const excel = await import('@/vendor/Export2Excel')
      excel.export_json_to_excel({
        header,
        data,
        filename: '员工信息表',
        autoWidth: true, // 宽度是否自适应
        bookType: 'xlsx' // 生成的文件类型
      })
    },
    // 数据转换
    formatJson(list) {
      const mapInfo = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      const header = Object.keys(mapInfo) // 英文 key
      return list.map((obj) => {
        const userInfo = {}
        header.forEach((item) => {
          // const enKey = obj[item]
          userInfo[mapInfo[item]] = obj[item]
        })
        return userInfo
      })
    },
    // 分配角色
    hAssignRole(id) {
      this.curId = id
      this.showDialogRole = true
      this.$nextTick(() => {
        this.$refs.AssignRole.getUserDetailById()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
</style>
